package com.example.aboutwork.forkjoin;

import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;

public class MyForkJoinThread {


    @SneakyThrows
    @Test
    public void test1() {
        ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
        CountDownLatch countDownLatch = new CountDownLatch(100000);
        long l = System.currentTimeMillis();
        int sum = 0 ;
        for (int i = 0; i < 100000; i++) {
            forkJoinPool.execute(new ComputeRunnable( sum, countDownLatch));
        }
        countDownLatch.await();
        System.err.println(System.currentTimeMillis() - l + "------"+sum);

    }


    @SneakyThrows
    @Test
    public void test2() {

        CountDownLatch countDownLatch = new CountDownLatch(100000);
        ExecutorService executorService = Executors.newFixedThreadPool(7);
        long l = System.currentTimeMillis();
        int sum = 0;
        for (int i = 0; i < 100000; i++) {
            executorService.execute(new ComputeRunnable( sum, countDownLatch));
        }
        countDownLatch.await();
        System.err.println(System.currentTimeMillis() - l + "----------" + sum);


    }


}

@AllArgsConstructor
class ComputeRunnable implements Runnable {
    int sum;
    CountDownLatch countDownLatch;

    @Override
    public void run() {
        System.err.println(sum);
        countDownLatch.countDown();
    }
}